0001    //
0002    //  BigUInt Random.swift
0003    //  BigInt
0004    //
0005    //  Created by Károly Lőrentey on 2016-01-04.
0006    //  Copyright © 2016 Károly Lőrentey. All rights reserved.
0007    //
0008    
0009    import Foundation
0010    
0011    extension BigUInt {
0012        //MARK: Random Integers
0013    
0014        /// Create a big integer consisting of `width` uniformly distributed random bits.
0015        ///
0016        /// - Returns: A big integer less than `1 << width`.
0017        /// - Note: This function uses `arc4random_buf` to generate random bits.
0018        @warn_unused_result
0019        public static func randomIntegerWithMaximumWidth
BigUInt Random.swift:43
        var result = randomIntegerWithMaximumWidth(width - 1)
BigUInt Random.swift:55
        var random = randomIntegerWithMaximumWidth(width)
BigUInt Random.swift:57
            random = randomIntegerWithMaximumWidth(width)
(width: Int) -> BigUInt { 0020 guard width > 0 else { return 0 } 0021 0022 let byteCount = (width + 7) / 8 0023 assert(byteCount > 0) 0024 0025 let buffer = UnsafeMutablePointer<UInt8>.alloc(byteCount) 0026 defer { buffer.destroy(byteCount) } 0027 0028 arc4random_buf(buffer, byteCount) 0029 if width % 8 != 0 { 0030 buffer[0] &= UInt8(1 << (width % 8) - 1) 0031 } 0032 0033 return BigUInt(NSData(bytesNoCopy: buffer, length: byteCount, freeWhenDone: false)) 0034 } 0035 0036 /// Create a big integer consisting of `width-1` uniformly distributed random bits followed by a one bit. 0037 /// 0038 /// - Returns: A random big integer whose width is `width`. 0039 /// - Note: This function uses `arc4random_buf` to generate random bits. 0040 @warn_unused_result 0041 public static func randomIntegerWithExactWidth(width: Int) -> BigUInt { 0042 guard width > 1 else { return BigUInt(width) } 0043 var result = randomIntegerWithMaximumWidth(width - 1) 0044 result[(width - 1) / Digit.width] |= 1 << Digit((width - 1) % Digit.width) 0045 return result 0046 } 0047 0048 /// Create a uniformly distributed random integer that's less than the specified limit. 0049 /// 0050 /// - Returns: A random big integer that is less than `limit`. 0051 /// - Note: This function uses `arc4random_buf` to generate random bits. 0052 @warn_unused_result 0053 public static func randomIntegerLessThan
BigUInt Prime Test.swift:112
            let random = BigUInt.randomIntegerLessThan(self)
(limit: BigUInt) -> BigUInt { 0054 let width = limit.width 0055 var random = randomIntegerWithMaximumWidth(width) 0056 while random >= limit { 0057 random = randomIntegerWithMaximumWidth(width) 0058 } 0059 return random 0060 } 0061 } 0062